package com.putong35.common.baseactfrag.refreshable.swiperefresh;


import android.content.Context;
import android.view.View;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.putong35.common.baseactfrag.refreshable.IRefreshable;
import com.putong35.common.baseactfrag.refreshable.OnRefreshListener;


/**
 * SwipeRefreshViewHelper
 *
 * @author Vivi Peng
 */
public class SwipeRefreshViewHelper implements IRefreshable {

    private Context mContext;
    private Object mComponent;
    private SwipeRefreshLayout mRefreshLayout;
    private OnRefreshListener mRefreshListener = null;

    public SwipeRefreshViewHelper(Context context, Object component) {
        mContext = context;
        mComponent = component;
    }


    /**
     * 这里不要调用Component的onStartRefreshing,会出现无限的递归调用
     *
     */
    @Override
    public void onStartRefreshing() {

    }

    /**
     * 隐藏刷新控件
     */
    public void hideRefreshView() {
        if (mRefreshLayout != null) {
            if (mRefreshLayout.isRefreshing()) {
                mRefreshLayout.setRefreshing(false);
            }
        }
    }


    /**
     * 显示刷新控件
     */
    public void showRefreshView() {
        if (mRefreshLayout != null) {
            if (!mRefreshLayout.isRefreshing()) {
                mRefreshLayout.setRefreshing(true);
            }
        }
    }


    /**
     * 设置是否需要下拉刷新的功能
     *
     * @param enable
     */
    public void setPullToRefreshEnable(boolean enable) {
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnabled(enable);
        }
    }

    /**
     * 设置向下滑动刷新的listener
     * user一般不需要设置这个东西，回调onStartRefreshing足够了。
     *
     * @param listener
     */
    public void setOnRefreshListener(OnRefreshListener listener) {
        mRefreshListener = listener;
        if(mRefreshLayout != null) {
            mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    mRefreshListener.onRefresh();
                }
            });
        } else {
            mRefreshLayout.setOnRefreshListener(null);
        }
    }

    public void initRefreshView(View refreshView, final IRefreshable refreshable) {
        if (refreshView != null && refreshView instanceof SwipeRefreshLayout) {
            mRefreshLayout = (SwipeRefreshLayout) refreshView;
            mRefreshLayout.setColorSchemeResources(android.R.color.holo_purple, android.R.color.holo_blue_bright,
                    android.R.color.holo_orange_light, android.R.color.holo_red_light);
            setOnRefreshListener(new OnRefreshListener() {

                @Override
                public void onRefresh() {
                    refreshable.onStartRefreshing();
                }
            });
        }
    }

}
